const amqp = require('amqplib/callback_api')

const URL = "iot.mq.rabbit.ztn-tech.com"
const PORT = 5672
const USER_NAME = "test"
const PASSWORD = "Ztn654321"
const EXCHANGE_NAME = "ztn.iot.sdk"
const QUEUE_BASE_NAME = "."
const IS_DURABLE = true


export function consumer(topic: String, msgHandler: Function) {
    const queueName = QUEUE_BASE_NAME + topic;
    amqp.connect(`amqp://${USER_NAME}:${PASSWORD}@${URL}:${PORT}`, function (err: any, conn: any) {
        const ok = conn.createChannel(on_open);

        function on_open(err: any, ch: any) {
            if (err != null) {
                throw new Error(err)
            }
            ch.assertExchange(EXCHANGE_NAME, "topic", {durable: true}, (ex: any) => {
                ch.assertQueue(queueName, {durable: IS_DURABLE, exclusive: false, autoDelete: !IS_DURABLE}, () => {
                    ch.bindQueue(queueName, ex.exchange, topic)
                    ch.consume(queueName, function (msg: any) {
                        if (msg !== null) {
                            msgHandler(msg.fields.exchange, JSON.parse(msg.content.toString()))
                            ch.ack(msg);
                        }
                    })
                })
            })
        }
    });
}

